package com.ansion.baseui.base;

import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;

import androidx.annotation.NonNull;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * created by zhaoyuntao
 * on 15/07/2022
 * description:
 */
class CompatForAndroid8 {
    static void tryToFixOrientation(@NonNull Activity activity) {
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray typedArray = activity.obtainStyledAttributes(styleableRes);
            Method method = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            method.setAccessible(true);
            if ((boolean) method.invoke(null, typedArray)) {
                try {
                    Field field = Activity.class.getDeclaredField("mActivityInfo");
                    field.setAccessible(true);
                    ActivityInfo o = (ActivityInfo) field.get(activity);
                    o.screenOrientation = SCREEN_ORIENTATION_UNSPECIFIED;
                    field.setAccessible(false);
                } catch (Exception e) {
                    e.printStackTrace();
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                }
            }
            method.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
